get.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from 'zod';
  3. import { SolutionDesignSchema } from '@/server/modules/solution-designs/solution-design.schema';
  4. import { ErrorSchema } from '@/server/utils/errorHandler';
  5. import { AppDataSource } from '@/server/data-source';
  6. import { SolutionDesignService } from '@/server/modules/solution-designs/solution-design.service';
  7. import { AuthContext } from '@/server/types/context';
  8. import { authMiddleware } from '@/server/middleware/auth.middleware';
  9. import { parseWithAwait } from '@/server/utils/parseWithAwait';
  10. // 路径参数Schema
  11. const GetParams = z.object({
  12. id: z.string().openapi({
  13. param: { name: 'id', in: 'path' },
  14. example: '1',
  15. description: '方案设计ID'
  16. })
  17. });
  18. // 路由定义
  19. const routeDef = createRoute({
  20. method: 'get',
  21. path: '/{id}',
  22. middleware: [authMiddleware],
  23. request: {
  24. params: GetParams
  25. },
  26. responses: {
  27. 200: {
  28. description: '成功获取方案设计详情',
  29. content: { 'application/json': { schema: SolutionDesignSchema } }
  30. },
  31. 400: {
  32. description: '请求参数错误',
  33. content: { 'application/json': { schema: ErrorSchema } }
  34. },
  35. 404: {
  36. description: '方案设计不存在',
  37. content: { 'application/json': { schema: ErrorSchema } }
  38. },
  39. 500: {
  40. description: '服务器错误',
  41. content: { 'application/json': { schema: ErrorSchema } }
  42. }
  43. }
  44. });
  45. // 路由实现
  46. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  47. try {
  48. const { id } = c.req.valid('param');
  49. const user = c.get('user');
  50. const service = new SolutionDesignService(AppDataSource);
  51. const result = await service.getById(Number(id), ['user', 'originalFile', 'outputFile', 'chapters']);
  52. if (!result) {
  53. return c.json({ code: 404, message: '方案设计不存在' }, 404);
  54. }
  55. // 检查权限:只能查看自己的方案设计
  56. if (result.userId !== user.id) {
  57. return c.json({ code: 403, message: '无权访问此方案设计' }, 403);
  58. }
  59. // 使用parseWithAwait处理Promise字段
  60. const validatedResult = await parseWithAwait(SolutionDesignSchema, result);
  61. return c.json(validatedResult, 200);
  62. } catch (error) {
  63. console.error('获取方案设计详情失败:', error);
  64. const { code = 500, message = '获取详情失败' } = error as Error & { code?: number };
  65. return c.json({ code, message }, code as 400 | 500 | 200 | 404 | 403);
  66. }
  67. });
  68. export default app;